package com.yanxu.threadpool;

import java.util.concurrent.*;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 折戟沉沙铁未销
 * @version V1.0
 * @date 2025/3/4-2025
 * @Description: 这里用一句话描述这个类的作用
 */
public class MyThreadPool extends ThreadPoolExecutor {
    private boolean isPaused;
    private static Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();


    public MyThreadPool(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
        super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
    }

    @Override
    protected void beforeExecute(Thread t, Runnable r) {
        super.beforeExecute(t, r);
        lock.lock();
        try {
            while (isPaused){
                condition.await();
            }
        }catch (InterruptedException e){
            e.printStackTrace();
        }finally {
            lock.unlock();
        }

    }

    @Override
    protected void afterExecute(Runnable r, Throwable t) {
        super.afterExecute(r, t);
    }


    public void pause() {
        lock.lock();
        try {
            isPaused = true;
        } finally {
            lock.unlock();
        }
    }

    public void resume(){
        lock.lock();
        try {
            isPaused=false;
            condition.signalAll();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPool myThreadPool =
                new MyThreadPool(10, 20, 60l,
                        TimeUnit.SECONDS, new ArrayBlockingQueue<>(1000));
        for (int i = 0; i < 1000; i++) {
            //提交任务
            myThreadPool.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println(Thread.currentThread().getName()+"执行了!!!");
                    try {
                        Thread.sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        Thread.sleep(100);
        myThreadPool.pause();
        System.out.println("线程池被暂停了!!!"+ System.currentTimeMillis());
        Thread.sleep(2000);
        myThreadPool.resume();
        System.out.println("线程池又被恢复了!!!"+System.currentTimeMillis());
    }

}